import socket


# A simple echo server for test

HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 891 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

while True:
    print "Waiting for connection"

    conn, addr = s.accept()

    print 'Connected by', addr

    while True:
        try:
            data = conn.recv(1024)
        except socket.error:
            print 'Disconnected by', addr
            break

        if not data:
            print 'Disconnected by', addr
            break

        print "Received:\n" + data

        if(data.startswith("L")):
            print "User login"
            conn.send(data)
        elif(data.startswith("R")):
            print "User Register"
            # NOTE : must have break line.
            conn.send("R Done\n")
        elif(data.startswith("S")):
            name = data.split()[1]
            print "Reset password for ", name
            conn.send("S %s\n" % name)
        elif(data.startswith("T")):
            print "User Publish"
            # NOTE : must have break line.
            conn.send("T Send\n")
    conn.close()
